package com.apply.inter;


import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.http.server.ServletServerHttpRequest;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.server.HandshakeInterceptor;

import com.apply.entity.User;

import javax.servlet.http.HttpSession;
import java.util.Map;

/**
 * websocket握手拦截�? * 拦截握手前，握手后的两个切面
 */
public class MyHandShakeInterceptor implements HandshakeInterceptor {

    public boolean beforeHandshake(ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse,
                                   WebSocketHandler webSocketHandler, Map<String, Object> map) throws Exception {

     
    	
    	
        if (serverHttpRequest instanceof ServletServerHttpRequest) {
        	
            ServletServerHttpRequest servletRequest = (ServletServerHttpRequest) serverHttpRequest;
            HttpSession session = servletRequest.getServletRequest().getSession(false);
            
            User user = (User) session.getAttribute("user");
            String registerId = String.valueOf(session.getAttribute("registerId"));           

            if(user!=null){
                map.put("uid", user.getId());//为服务器创建WebSocketSession做准�? 
            }else if(registerId!=null){
            	map.put("uid",Integer.parseInt(registerId));      	
            }else{
               
                return false;
            }
        }
        return true;
    }
    
    

    public void afterHandshake(ServerHttpRequest serverHttpRequest,
                               ServerHttpResponse serverHttpResponse,
                               WebSocketHandler webSocketHandler, Exception e) {

    }
}
